<?php
include 'config.php';

class PP {
  private static $link;
  private static $results=array();

  public static function log($v) {
    echo '<p>'.str_replace('\n', '<br/>', htmlspecialchars($v)).'</p>';
  }

  public static function log_r($v) {
    echo '<pre>';
    print_r($v);
    echo '</pre>';
  }

  public static function getUrl($type) {
    switch($type) {
      case 'index':
        return PP_ROOT."/index.php";
      case 'kml':
        return PP_ROOT."/map.php";
      case 'map':
        return "http://maps.google.com/maps?q=".urlencode(PP::getUrl('kml').'?rnd='.(int)(time()/3));
    }
    return "";
  }

  public static function getLink($type, $text) {
    return '<a href="' . PP::getUrl($type) . '">' . $text . '</a>';
  }

  public static function pp_validate_email($email) {
    return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
  }

  /**
   * Connect to the db
   */
  public static function connect() {
    if (!self::$link) {
      self::$link = mysql_connect(PP_HOST, PP_USER, PP_PASSWORD)
        or die('Could not connect: ' . mysql_error());
      mysql_select_db(PP_NAME)
        or die('Could not select database');
    }
  }

  /**
   * Query the database. Note that the returned result should not be freed -
   * that is automatically handled by PP::disconnect
   */
  public static function query($sql) {
    // PP::log($sql);

    PP::connect();
    $result = mysql_query($sql, self::$link);
    if ($result) {
      if (!is_bool($result)) {
        self::$results[] = $result;
      }
    } else {
      PP::log($sql);
      die('Invalid query: ' . mysql_error());
    }
    return $result;
  }

  /**
   * Free all results, and disconnect from the db.
   */
  public static function disconnect() {
    if (PP::$link) {
      // Free results
      foreach (self::$results as $result) {
        mysql_free_result($result);
      }

      // Close connection
      mysql_close(self::$link);
      self::$link = NULL;
    }
  }
}

